<template>
  <div id="cesiumContainer"></div>
</template>

<script setup>
// 导入 cesium
import * as Cesium from 'cesium'
// 导入 vue 的API
import { onMounted } from 'vue'

onMounted(() => {
  // 设置 token
  Cesium.Ion.defaultAccessToken =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4ZWQzZDcwMi04MGVhLTQ5ZjItOTRkZi1hNzBhOWU4OTZjMjEiLCJpZCI6MTE2MzEzLCJpYXQiOjE2Njk2MTgyNTR9.5Z_xgcUM3VKaK1ZdOQkz6Vma-jsf1JYnd3sFUEB6Je4'

  // 加载街道地图
  // const custom = new Cesium.ArcGisMapServerImageryProvider({
  //   url: 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer'
  // })

  // 初始化Cesium界面
  const viewer = new Cesium.Viewer('cesiumContainer', {
    infoBox: false
    // imageryProvider: custom
  })

  // 添加纽约市 3DTiles 数据
  const city = viewer.scene.primitives.add(
    new Cesium.Cesium3DTileset({
      url: Cesium.IonResource.fromAssetId(75343)
    })
  )
  viewer.flyTo(city)

  // 为城市建筑物以不同高度设置颜色分类
  city.style = new Cesium.Cesium3DTileStyle({
    color: {
      conditions: [
        ['${Height} >= 300', 'rgba(45,0,75,0.9)'],
        ['${Height} >= 200', 'rgba(102,71,151,0.9)'],
        ['${Height} >= 150', 'rgba(170,162,204,0.9)'],
        ['${Height} >= 100', 'rgba(224,226,238,0.9)'],
        ['${Height} >= 80', 'rgba(252,230,200,0.9)'],
        ['${Height} >= 50', 'rgba(248,176,87,0.9)'],
        ['${Height} >= 10', 'rgba(198,106,11,0.9)'],
        ['true', 'rgba(127, 59, 8,0.9)']
      ]
    }
  })

  // 加载 Geojson 数据
  const neighborHoodsPromise = Cesium.GeoJsonDataSource.load(
    './assets/SampleData/sampleNeighborhoods.geojson'
  )
  let neighborHoods
  neighborHoodsPromise.then((dataSource) => {
    // 将Geojson添加到 viewer 视图中
    viewer.dataSources.add(dataSource)
    neighborHoods = dataSource.entities
    // 获取Geojson的每一块实体，并进行循环
    let neighborHoodsEntities = dataSource.entities.values
    for (let i = 0; i < neighborHoodsEntities.length; i++) {
      let entity = neighborHoodsEntities[i]
      if (Cesium.defined(entity.polygon)) {
        // 设置多边形名称
        entity.name = entity.properties.neighborhood._value
        // 设置多边形材质(随机色)
        entity.polygon.material = new Cesium.Color.fromRandom({
          minimumRed: 0.75,
          maximumRed: 1,
          minimumGreen: 0.75,
          maximumGreen: 1,
          minimumBlue: 0.75,
          maximumBlue: 1,
          minalpha: 0.5
        })

        entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN

        let ployPositions = entity.polygon.hierarchy.getValue(
          Cesium.JulianDate.now()
        ).positions
        let ployCenter = Cesium.BoundingSphere.fromPoints(ployPositions).center
        ployCenter = Cesium.Ellipsoid.WGS84.scaleToGeocentricSurface(ployCenter)
        entity.position = ployCenter

        // 生成标签
        entity.label = {
          text: entity.name,
          showBackground: true,
          scale: 0.6,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            10,
            8000
          ),
          disableDepthTestDistance: 100
        }
      }
    }
  })

  var kmlOptions = {
    camera: viewer.scene.camera,
    canvas: viewer.scene.canvas,
    // 如果我们想要将几何特征（多边形、线串和线性环）固定在地面上，则为true
    clampToGround: true
  }

  var geocachePromise = Cesium.KmlDataSource.load(
    './assets/SampleData/sampleGeocacheLocations.kml',
    kmlOptions
  )

  // 将 geocache 广告牌实体添加到场景中并为其设置样式
  geocachePromise.then(function (dataSource) {
    // 将新数据作为实体添加到查看器
    viewer.dataSources.add(dataSource)

    // 获取实体数组
    var geocacheEntities = dataSource.entities.values

    for (var i = 0; i < geocacheEntities.length; i++) {
      var entity = geocacheEntities[i]
      if (Cesium.defined(entity.billboard)) {
        // 调整垂直原点，使图钉位于地形上
        entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM
        entity.billboard.image = '/assets/tagpark.png'
        // 禁用标签以减少混乱
        entity.label = undefined
        // 添加距离显示条件
        entity.billboard.distanceDisplayCondition =
          new Cesium.DistanceDisplayCondition(10.0, 20000.0)
      }
    }
  })

  // 从czml文件加载飞行路径
  var dronePromise = Cesium.CzmlDataSource.load(
    './assets/SampleData/sampleFlight.czml'
  )

  var drone
  dronePromise.then(function (dataSource) {
    viewer.dataSources.add(dataSource)
    drone = dataSource.entities.getById('Aircraft/Aircraft1')

    drone.model = {
      // uri: './assets/SampleData/Models/CesiumDrone.gltf',
      uri: './assets/SampleData/Models/ferrari2.gltf',
      minimumPixelSize: 128,
      maximumScale: 1000,
      silhouetteColor: Cesium.Color.WHITE,
      silhouetteSize: 2
    }

    drone.orientation = new Cesium.VelocityOrientationProperty(drone.position)
    drone.viewFrom = new Cesium.Cartesian3(0, -30, 30)
    viewer.clock.shouldAnimate = true
  })
})
</script>

<style></style>
